import axios from 'axios'
import { throwErr } from './message.config' // 捕捉服务端http状态码的方法
import { Toast } from 'mint-ui';
import { Indicator } from 'mint-ui';

//过滤请求
axios.interceptors.request.use(config => {
  Indicator.open({
    text: '加载中...',
    spinnerType: 'fading-circle'
  });
  config.timeout = 100 * 1000 //请求响应时间
  return config
}, error => {
  Indicator.close();
  Toast({
    message: '加载超时',
    duration: 2000
  });
  return Promise.reject(error)
});
// 添加响应拦截器
axios.interceptors.response.use(
    response => {
      Indicator.close();
      // if (response.data.code === 0) {   //服务端定义的响应code码为1时请求成功
        return Promise.resolve(response.data) //使用Promise.resolve 正常响应
      // }  else {
      //   Toast(response.data.msg);
      //   return Promise.reject(response.data)
      // }
    },
    error => {
      Indicator.close();
      if (error && error.response) {
        let res = {}
        res.code = error.response.status
        res.msg = throwErr(error.response.status, error.response)
        Toast(res.msg);
        return Promise.reject(res)
      }
      return Promise.reject(error)
    }
)

// axios.defaults.headers = {"Content-Type": "application/json"}

function formatParams (data) {
  if (data && typeof data === 'object') {
    let form = new FormData()
    Object.keys(data).forEach(key => {
      form.append(key, data[key])
    })
    return form
  } else {
    return {}
  }
}

export default function request(method, url, data) {  //暴露 request 给我们好API 管理
  method = method.toLocaleLowerCase()   //封装RESTful API的各种请求方式 以 post get delete为例
  if (method === 'post') {
    return axios.post(url, data)    //axios的post 默认转化为json格式
  } else if (method === 'get') {
    return axios.get(url, {
      params: data
    })
  } else if (method === 'delete') {
    return axios.delete(url, {
      params: data
    })
  }
}

